#!/usr/local/bin/python2.4

import icon
import string

# This is the 8 queens program as close as I can make it to the 
# verison in chapter 17 of The Icon Programming Language 3rd ed.

# A helper function to initialize lists
def mklist(length, initializer):
    return [initializer for _ in xrange(0, length)]


# Increase list length because Python indexing starts at 0
up = mklist(16, 0)
down = mklist(16, 0)
row = mklist(9, 0)


# This function is a Python iterator and I'd like to replace it with 
# an icon.Generator, but I don't know how to emulate yield in Python.
#
# I have no way to do automatic data backtracking, so I do it manually after
# resuming.
#
# Also, in Python, = is not an expression, so it can't be yielded directly.
def place(r, c):
    if row[r] == down[r + c - 1] == up[8 + r - c] == 0:
        row[r] = down[r + c - 1] = up[8 + r - c] = r
        yield r
        row[r] = down[r + c - 1] = up[8 + r - c] = 0


# Yield a sequence of the legal rows for a queen in column c
def q(c):
    return icon.apply(lambda r: place(r, c), xrange(1, 9))


# The write function, which receives row positions as an argument tuple
def write(*rows):
    print string.join(map(str, rows), "")


def main():
    icon.first_do(write, q(1), q(2), q(3), q(4), q(5), q(6), q(7), q(8))

main()
